package com.canvas;


import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;

import com.bd.dal;
import com.encuestas.utilidades;
import com.medios.imark.encuesta.R;


import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.SQLException;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;

public class firma extends Activity {

	LinearLayout mContent;
	public lienzo mSignature;
	 public Button btnlimpiar;
	 public Button btnguardar;
	 public Button btncancelar;
	    public static String tempDir;
	    public int count = 1;
	    public String current = null;
	    public static Bitmap mBitmap;
	    public View mView;
	    public File mypath, mypathm, mypathb;
	    private String uniqueId;
	    dal dto;
	   public int proyecto, formulario, encuestador;
	  public String imei;
	
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		  this.requestWindowFeature(Window.FEATURE_NO_TITLE);
	        setContentView(R.layout.firma);
	        Intent g = getIntent();
	        proyecto = Integer.parseInt(g.getStringExtra("proyecto"));
	        formulario = Integer.parseInt(g.getStringExtra("formulario"));
	        encuestador = Integer.parseInt(g.getStringExtra("encuestador"));
	        imei = g.getStringExtra("imei");
	        
	        
	       // File directory = new File(Environment.getExternalStorageDirectory() + "/GLP_Images");
	        File directory= new File("mnt/sdcard"+ File.separator +"firmamin");
	        File directory1= new File("mnt/sdcard"+ File.separator +"firmamed");
	        File directory2= new File("mnt/sdcard"+ File.separator +"firmabig");

	        if(!directory.exists())
	         
	            directory.mkdir(); //directory is created;
	        if(!directory1.exists())
		         
	        	directory1.mkdir();
	             if(!directory2.exists())
	         
	            	 directory2.mkdir();
	            
	        dto = new dal(this);
	        //uniqueId = getTodaysDate() + "_" + getCurrentTime();
	        uniqueId=""+ proyecto +"_" + formulario + "_" + encuestador + "_" + imei;
	        current = uniqueId + ".png";
	        mypath= new File(directory,current);
	        mypathm= new File(directory1,current);
	        mypathb= new File(directory2,current);
	        
	        
	        mContent = (LinearLayout) findViewById(R.id.hoja);
	        mSignature = new lienzo(this, null);
	        mSignature.setBackgroundColor(Color.WHITE);
	        mContent.addView(mSignature, LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
	        btnlimpiar = (Button)findViewById(R.id.btnlimpiarfirma);
	        btnguardar = (Button)findViewById(R.id.btnguardarfirma);
	        btnguardar.setEnabled(false);
	        btncancelar = (Button)findViewById(R.id.btncancelarfirma);
	        mView = mContent;
	        
	        btnlimpiar.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					
					mSignature.clear();
					btnguardar.setEnabled(false);
					
				}
			});
	        
	        
	        btncancelar.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
				
					Log.v("log_tag", "Panel Canceled");
	                Bundle b = new Bundle();
	                b.putString("status", "cancel");
	                Intent intent = new Intent();
	                intent.putExtras(b);
	                setResult(RESULT_CANCELED,intent); 
	                finish();
					
					
				}
			});
	        
	        btnguardar.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					  mView.setDrawingCacheEnabled(true);
	                    mSignature.save(mView);
	                    
	                    try
	                    {
	                   // dto.insertarBitmap(mBitmap);
	                    if(!dto.existeImagen(proyecto, formulario, 230))
	                    {
	                    	   dto.insertarBitmap(mBitmap,proyecto, formulario, encuestador, 230, imei);
	                    	
	                    }
	                    
	                    else
	                    {
	                    	dto.updateImagen(mBitmap, proyecto, formulario, encuestador, 230, imei);
	                    	
	                    }
	                    }
	                    catch (Exception e)
	                    {
	                    	
	                    	Log.e("ERROR DE GUARDAR FIRMA", e.getMessage());
	                    	
	                    }
	                    
	                    	
	                
	                   Bundle b = new Bundle();
	                     b.putString("status", "done");
	                     Intent intent = new Intent();
	                     intent.putExtras(b);
	                  setResult(RESULT_OK );  
	                    finish();
					
				}
			});
		
	}
	
	
	private boolean makedirs()	
    {
        File tempdir = new File(tempDir);
        if (!tempdir.exists())
            tempdir.mkdirs();

        if (tempdir.isDirectory())
        {
            File[] files = tempdir.listFiles();
            for (File file : files)
            {
                if (!file.delete())
                {
                    System.out.println("Failed to delete " + file);
                }
            }
        }
        return (tempdir.isDirectory());
    }	
	
	private String getTodaysDate() 
    {

        final Calendar c = Calendar.getInstance();
        int todaysDate =     (c.get(Calendar.YEAR) * 10000) +
        ((c.get(Calendar.MONTH) + 1) * 100) +
        (c.get(Calendar.DAY_OF_MONTH));
        Log.w("DATE:",String.valueOf(todaysDate));
        return(String.valueOf(todaysDate));

    }

    private String getCurrentTime() 
    {

        final Calendar c = Calendar.getInstance();
        int currentTime =     (c.get(Calendar.HOUR_OF_DAY) * 10000) +
        (c.get(Calendar.MINUTE) * 100) +
        (c.get(Calendar.SECOND));
        Log.w("TIME:",String.valueOf(currentTime));
        return(String.valueOf(currentTime));

    }


	class lienzo extends View {

		private static final float STROKE_WIDTH = 5f;
        private static final float HALF_STROKE_WIDTH = STROKE_WIDTH / 2;
        private Paint paint = new Paint();
        private Path path = new Path();
		
        
        private float ultimotoqueX;
        private float ultimotoqueY;
        private final RectF dirtyRect = new RectF();
		
		public lienzo(Context context, AttributeSet attrs) {
			super(context,attrs );
			  paint.setAntiAlias(true);
	            paint.setColor(Color.BLACK);
	            paint.setStyle(Paint.Style.STROKE);
	            paint.setStrokeJoin(Paint.Join.ROUND);
	            paint.setStrokeWidth(STROKE_WIDTH);
	            
		}
		
		
		
	      /**
	     * @param v
	     */
	    public void save(View v)
	        {
	            Log.v("log_tag", "Width: " + v.getWidth());
	            Log.v("log_tag", "Height: " + v.getHeight());
	        
	            if(mBitmap == null)
	            {
	                mBitmap =  Bitmap.createBitmap (mContent.getWidth(), mContent.getHeight(), Bitmap.Config.RGB_565);
	            }
	            Canvas canvas = new Canvas(mBitmap);
	            try
	            {
	            	
	            	
	        	
	                FileOutputStream mFileOutStream = new FileOutputStream(mypath);
	             //  FileOutputStream mFileOutStreamm = new FileOutputStream(mypathm);
	               // FileOutputStream mFileOutStreamb = new FileOutputStream(mypathb);*/

	                v.draw(canvas);
	                mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, mFileOutStream);
	             //mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStreamm);
	               // mBitmap.compress(Bitmap.CompressFormat.PNG, 90, mFileOutStreamb);*/
	                
	               mFileOutStream.flush();
	               mFileOutStream.close();
	             /*  mFileOutStreamm.flush();
	               mFileOutStreamm.close();*/
	              /* mFileOutStreamb.flush();
	               mFileOutStreamb.close();*/
	               
	               
	              //  String url = Images.Media.insertImage(getContentResolver(), mBitmap, "title", null);
	                //Log.v("log_tag","url: " + url);
	                
//	                //In case you want to delete the file
//	                boolean deleted = mypath.delete();
//	                Log.v("log_tag","deleted: " + mypath.toString() + deleted);
//	                //If you want to convert the image to string use base64 converter
	                

	            }
	            catch(Exception e)
	            {
	                Log.v("log_tag", e.toString());
	            }
	        }

		
		@Override
		protected void onDraw(Canvas canvas) {
			 canvas.drawPath(path, paint);
			
		}
		
		
		@Override
		public boolean onTouchEvent(MotionEvent event) {
			
			 float eventX = event.getX();
	            float eventY = event.getY();
	          btnguardar.setEnabled(true);

	            switch (event.getAction())
	            {
	            case MotionEvent.ACTION_DOWN:
	                path.moveTo(eventX, eventY);
	                ultimotoqueX = eventX;
	                ultimotoqueY = eventY;
	                return true;

	            case MotionEvent.ACTION_MOVE:

	            case MotionEvent.ACTION_UP:

	                resetDirtyRect(eventX, eventY);
	                int historySize = event.getHistorySize();
	                for (int i = 0; i < historySize; i++)
	                {
	                    float historicalX = event.getHistoricalX(i);
	                    float historicalY = event.getHistoricalY(i);
	                    expandDirtyRect(historicalX, historicalY);
	                    path.lineTo(historicalX, historicalY);
	                }
	                path.lineTo(eventX, eventY);
	                break;

	            default:
	                debug("Ignored touch event: " + event.toString());
	                return false;
	            }

	            invalidate((int) (dirtyRect.left - HALF_STROKE_WIDTH),
	                    (int) (dirtyRect.top - HALF_STROKE_WIDTH),
	                    (int) (dirtyRect.right + HALF_STROKE_WIDTH),
	                    (int) (dirtyRect.bottom + HALF_STROKE_WIDTH));

	            ultimotoqueX = eventX;
	            ultimotoqueY = eventY;

	            return true;
			
		}
		
		private void debug(String string)
        {
        }
		  private void expandDirtyRect(float historicalX, float historicalY)
	        {
	            if (historicalX < dirtyRect.left)
	            {
	                dirtyRect.left = historicalX;
	            }
	            else if (historicalX > dirtyRect.right)
	            {
	                dirtyRect.right = historicalX;
	            }

	            if (historicalY < dirtyRect.top)
	            {
	                dirtyRect.top = historicalY;
	            }
	            else if (historicalY > dirtyRect.bottom)
	            {
	                dirtyRect.bottom = historicalY;
	            }
	        }
		  
		  
		
		  private void resetDirtyRect(float eventX, float eventY)
	        {
	            dirtyRect.left = Math.min(ultimotoqueX, eventX);
	            dirtyRect.right = Math.max(ultimotoqueX, eventX);
	            dirtyRect.top = Math.min(ultimotoqueY, eventY);
	            dirtyRect.bottom = Math.max(ultimotoqueY, eventY);
	        }
		
		
		public void clear()
        {
            path.reset();
            invalidate();
        }
		
		
	}
	
}
